import { z } from '@vben/common-ui'
import { $t } from '@vben/locales'
import { isHttpLink, isIdCard, isPhone } from './validator'

/**
 * 通用函数
 * @param refine 校验函数
 */
export const formValidFormat = function (
    refine: (value: string) => boolean,
    opts?: { label?: string; message?: string; required?: boolean }
) {
    const { label = $t('common.format'), required = true, message } = opts || {}
    return required
        ? z
              .string()
              .min(1, { message: $t('ui.formRules.minLength', ['', 1]) })
              .refine(refine, {
                  message: message || $t('common.form.rightInput', { label })
              })
        : z
              .string()
              .refine(refine, {
                  message: message || $t('common.form.rightInput', { label })
              })
              .optional()
}

/**
 * 手机号码格式
 */
export const formValidMobile = function (opts?: { label?: string; required?: boolean }) {
    const { label = $t('authentication.mobile'), required = true } = opts || {}
    return formValidFormat(isPhone, { label, required })
}

/**
 * 身份证号
 */
export const formValidIdCard = function (opts?: { label?: string; required?: boolean }) {
    const { label = $t('common.idCard'), required = true } = opts || {}
    return formValidFormat(isIdCard, { label, required })
}

/**
 * 链接格式
 */
export const formValidHttpLink = function (opts?: { label?: string; required?: boolean }) {
    const { label = $t('common.link'), required = true } = opts || {}
    return formValidFormat(isHttpLink, { label, required })
}
